﻿
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.Configuration;
using SqlSugar;
using System.Diagnostics;
using Quartz;
using Autofac;
using 微信机器人服务.Quartz;
using 微信机器人服务.Models;
using WeChatBotSDK.Events;
using WeChatBotSDK.Enums;
using WeChatBotSDK.Models;
using WeChatBotSDK.Interfaces;
using 微信机器人服务.Service;
using WeChatBotSDK.Constants;
using System.Text.RegularExpressions;
using WeChatBotSDK.Utilities;

namespace 微信机器人服务.Services
{
    public class StartSystemJob : BackgroundService
    {
        private IConfiguration _configuration { get; }
        private readonly ILogger<StartSystemJob> _logger;
        private readonly DatabaseInitializer _databaseInitializer;
        private readonly IQuartzJobsFactory _quartzJobsFactory;
        private readonly ILifetimeScope AutofacContainer;
        private readonly IQXApiService _QXApiService;
        private readonly IWeChatApiService _weChatApiService;
        public StartSystemJob(IConfiguration configuration, ILogger<StartSystemJob> logger, IQuartzJobsFactory quartzJobsFactory,ILifetimeScope AutofacContainer, IQXApiService qxChatApiService, IWeChatApiService weChatApiService, DatabaseInitializer databaseInitializer)
        {
            _configuration = configuration;
            _logger = logger;
            //_sqlSugarClient = sqlSugarClient.AsTenant().GetConnectionScope("能源");
            _quartzJobsFactory = quartzJobsFactory;
            this.AutofacContainer = AutofacContainer;
            _QXApiService = qxChatApiService;
            _weChatApiService = weChatApiService;
            _databaseInitializer = databaseInitializer;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            if (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("开始启动: {time}", DateTimeOffset.Now);
                try
                {
                    _databaseInitializer.Initialize();
                    EventHandlers.OnMessage= async (data) =>
                    {
                        if (data.Data?.Data.MsgType == MsgType.Text)
                        {
                            WeChatResponse<object>? 发送结果;
                            if (data.Data.Data.Msg == "图片")
                            {
                                发送结果 = await _QXApiService.SendImageAsync(data.Data.Wxid, data.Data.Data.FromWxid, @"C:\Users\Administrator\Desktop\服务器IP.jpg");
                            }
                            else if (data.Data.Data.Msg == "文件")
                            {
                                发送结果 = await _QXApiService.SendFileAsync(data.Data.Wxid, data.Data.Data.FromWxid, @"C:\Users\Administrator\Desktop\新建文本文档.txt");
                            }
                            else
                            {
                                发送结果 = await _QXApiService.SendTextMessageAsync(data.Data.Wxid, data.Data.Data.FromWxid, data.Data.Data.Msg);
                            }

                            if (发送结果.IsSuccess)
                            {
                                _logger.LogInformation($"发送图片成功，好友 WXID: {data.Data.Data.FromWxid}, 消息内容: {data.Data.Data.Msg}");
                            }
                            else
                            {
                                _logger.LogInformation($"发送图片失败，好友 WXID: {data.Data.Data.FromWxid}, 消息内容:  {data.Data.Data.Msg}");
                            }
                        }
                    };

                    EventHandlers.OnAccountChangeEvent= async (data) =>
                    {
                        if (data.Data.Type == OnlineStatus.Online)
                        {
                            var friendList = await _QXApiService.GetFriendListAsync(data.Data.Wxid);
                            var firstWxid = friendList.Result.FirstOrDefault()?.Wxid;
                            if (firstWxid != null)
                            {
                                var 结果 = await _QXApiService.SendTextMessageAsync(data.Data.Wxid, firstWxid, $"[{data.Data.Nick}]上线了！[呲牙]");

                                if (结果.IsSuccess)
                                {
                                    _logger.LogInformation($"发送消息成功，好友 WXID: {firstWxid}, 消息内容: [{data.Data.Nick}]上线了！[呲牙]");
                                }
                                else
                                {
                                    _logger.LogInformation($"发送消息失败，好友 WXID: {firstWxid}, 消息内容: [{data.Data.Nick}]上线了！[呲牙]");
                                }

                            }

                        }
                    };


                    EventHandlers_D.OnMessage = async (data) =>
                    {
                        switch (data.Data.MsgType)
                        {
                            case MsgType.Text:
                                WeChatResponse<object>? 发送结果;
                                if (data.Data.Msg == "图片")
                                {
                                    发送结果 = await _weChatApiService.SendImageAsync(data.Wxid, data.Data.FromWxid, @"C:\Users\Administrator\Desktop\服务器IP.jpg");
                                }
                                else if (data.Data.Msg == "文件")
                                {
                                    发送结果 = await _weChatApiService.SendFileAsync(data.Wxid, data.Data.FromWxid, @"C:\Users\Administrator\Desktop\新建文本文档.txt");
                                }
                                else
                                {
                                    发送结果 = await _weChatApiService.SendTextMessageAsync(data.Wxid, data.Data.FromWxid, data.Data.Msg);
                                }

                                if (发送结果.IsSuccess)
                                {
                                    _logger.LogInformation($"发送图片成功，好友 WXID: {data.Data.FromWxid}, 消息内容: {data.Data.Msg}");
                                }
                                else
                                {
                                    _logger.LogInformation($"发送图片失败，好友 WXID: {data.Data.FromWxid}, 消息内容:  {data.Data.Msg}");
                                }
                                break;
                            case MsgType.Image:
                                // 定义正则表达式
                                string pattern = @"pic=(?<picPath>.*?),isDecrypt=(?<isDecrypt>\d)";

                                // 匹配消息文本
                                Match match = Regex.Match(data.Data.Msg, pattern);

                                if (match.Success)
                                {
                                    // 提取图片路径
                                    string picPath = match.Groups["picPath"].Value;

                                    // 提取解密状态
                                    string isDecrypt = match.Groups["isDecrypt"].Value;

                                    // 打印结果
                                    Console.WriteLine($"图片路径: {picPath}");
                                    Console.WriteLine($"是否解密: {isDecrypt}");


                                    if (isDecrypt=="1")
                                    {
                                        var 扩展名=Path.GetExtension(picPath);
                                        var res= await _weChatApiService.DownloadFileOrImageAsync(picPath);
                                        File.WriteAllBytes($"{DateTime.Now:yyyyMMddHHmmss}{扩展名}", res);
                                    }
                                    else
                                    {
                                        //await _weChatApiService.DecryptDatImageAsync(picPath,);
                                    }


                                    
                                }
                                else
                                {
                                    Console.WriteLine("无法解析消息文本！");
                                }
                        
                                break;
                            case MsgType.Voice:
                                break;
                            case MsgType.ContactCard:
                                break;
                            case MsgType.Video:
                                break;
                            case MsgType.AnimatedEmoji:
                                break;
                            case MsgType.Location:
                                break;
                            case MsgType.LinkOrFile:
                                break;
                            case MsgType.RedPacket:
                                break;
                            case MsgType.MiniProgram:
                                break;
                            case MsgType.GroupInvite:
                                break;
                            case MsgType.SystemMessage:
                                break;
                            default:
                                break;
                        }

                    };

                    EventHandlers_D.OnAccountChangeEvent = async (data) =>
                    {
                        if (data.Type == WechatEventTypes.D_LoginSuccess)
                        {
                            var friendList = await _weChatApiService.GetFriendListAsync(data.Data.Wxid);
                            var firstWxid = friendList.Result.FirstOrDefault()?.Wxid;
                            if (firstWxid != null)
                            {
                                var 结果 = await _weChatApiService.SendTextMessageAsync(data.Data.Wxid, firstWxid, $"[{data.Data.Nick}]上线了！[呲牙]");

                                if (结果.IsSuccess)
                                {
                                    _logger.LogInformation($"发送消息成功，好友 WXID: {firstWxid}, 消息内容: [{data.Data.Nick}]上线了！[呲牙]");
                                }
                                else
                                {
                                    _logger.LogInformation($"发送消息失败，好友 WXID: {firstWxid}, 消息内容: [{data.Data.Nick}]上线了！[呲牙]");
                                }

                            }

                        }
                    };






                    var scheduler = AutofacContainer.Resolve<IScheduler>();
                    await scheduler.Start();

                    var jobInfos = _configuration.GetSection("JobInfos").Get<List<JobInfo>>() ?? [];

                    foreach (var item in jobInfos)
                    {
                        if (item.启用 && !string.IsNullOrWhiteSpace(item.JobName) && !string.IsNullOrWhiteSpace(item.CronExpression))
                        {
                            await _quartzJobsFactory.CreateJobAsync(item.JobName, item.CronExpression);
                        }
                    }

                    _ = Task.Run(() =>
                    {
                        ConfigJsonSettings configJsonSection=_configuration.GetSection("ConfigJson").Get<ConfigJsonSettings>()!;

                        注入工具.SetupWeChat(configJsonSection.WxPath, configJsonSection.Port, configJsonSection.CallBackUrl, configJsonSection.CacheData, configJsonSection.DecryptImg, configJsonSection.TimeOut, configJsonSection.Flag, configJsonSection.Ver, configJsonSection.NoHandleMsg, configJsonSection.AutoLogin);
                    });


                }
                catch(Exception ex)
                {
                    _logger.LogError(ex, "启动失败");
                }
                
                
            }
            else
            {
                await StopAsync(stoppingToken);
            }
        }
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            return base.StartAsync(cancellationToken);
        }
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            return base.StopAsync(cancellationToken);
        }
    }
}
